package com.codecash.controller;


import com.codecash.controller.response.Result;
import com.codecash.entity.Post;
import com.codecash.service.PostService;
import com.codecash.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/community/post")
public class PostController {
    @Autowired
    private PostService postService;

    //发布帖子
    @PostMapping("/create")
    public Result add(@RequestBody @Validated Post post) {
        // 检查帖子类型是否为 "programmer", "task" 或 "community"
        if (!("programmer".equals(post.getPostType()) || "task".equals(post.getPostType()) || "community".equals(post.getPostType()))) {
            return Result.error("帖子类型只能为 programmer, task 或 community");
        }

        postService.add(post);
        return Result.success();
    }

    //查询帖子
    @GetMapping("/detail/{id}")
    public Result getPostDetail(@PathVariable Long id) {
        Post post = null;
        try {
            post = postService.getPostById(id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (post == null) {
            return Result.error("帖子不存在");
        }
        return Result.success(post);
    }

    // 修改帖子
    @PostMapping("/update")
    public Result update(@RequestBody @Validated Post post) {
        try {
            postService.update(post);
            return Result.success("帖子更新成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    // 校验帖子类型是否合法
    private boolean isValidPostType(String postType) {
        return "programmer".equals(postType) || "task".equals(postType) || "community".equals(postType);
    }

    //删除帖子
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        try {
            postService.delete(id);
            return Result.success("帖子删除成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    // 查询所有帖子
    @GetMapping("/all")
    public Result<List<Post>> getAllPosts() {
        List<Post> posts = postService.findAllPosts();
        return Result.success(posts);
    }
    // 查询我所有帖子
    @GetMapping("/allmypost")
    public Result<List<Post>> getAllmyPosts() {
        // 从 ThreadLocal 获取当前用户的 ID
        Map<String, Object> map = ThreadLocalUtil.get();
        Long currentUserId = ((Number) map.get("id")).longValue();

        // 调用服务层方法，查询当前用户的帖子
        List<Post> posts = postService.findAllmyPosts(currentUserId);
        return Result.success(posts);
    }


}